package com.cheil.publish.web;

import com.alibaba.fastjson2.JSON;
import com.cheil.publish.service.ai.DashscopeService;
import com.cheil.publish.service.data.ChatsDto;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.concurrent.CompletableFuture;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.ai.image.ImageResponse;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

/**
 * @author ssk
 * @date 2025/9/5
 **/
@Tag(name = "首页")
@Controller
@AllArgsConstructor
@Log4j2
public class IndexController {
    private final DashscopeService dashscopeService;

    @GetMapping("/index")
    public String hello() {
        return "index";
    }

    @GetMapping(value = "/ask", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @ResponseBody
    public SseEmitter ask(@RequestParam String message) {
        SseEmitter emitter = new SseEmitter(Long.MAX_VALUE);

        CompletableFuture.runAsync(() -> {
            try {
                // 发送处理中的消息（在实际数据开始前）
                emitter.send(SseEmitter.event().name("processing").data("收到消息: \"" + message + "\"，正在处理中..."));
                emitter.send(SseEmitter.event().name("message").data("开始处理消息...\n"));

                ChatsDto chatsDto = dashscopeService.chat(message);
                log.info("chat res:{}", JSON.toJSONString(chatsDto));
                emitter.send(SseEmitter.event().name("message").data(chatsDto.content()));
                emitter.send(SseEmitter.event().name("message").data("处理完成\n"));
                ImageResponse imageResponse = dashscopeService.generateImage(chatsDto.content());
                emitter.send(SseEmitter.event().name("message").data(imageResponse.getResult().getOutput().getUrl()));
                emitter.send(SseEmitter.event().name("message").data("图片生成完成\n"));

                // 处理 dashscopeService.chat 返回的消息
//                dashscopeService.chatStream(message)
//                    .subscribe(
//                        data -> {
//                            try {
//
//                                for (char c : data.toCharArray()) {
//                                    emitter.send(SseEmitter.event().name("message").data(String.valueOf(c)));
//                                }
//                            } catch (IOException e) {
//                                log.error("发送消息失败", e);
//                                emitter.completeWithError(e);
//                            }
//                        }
//                        ,
//                        error -> {
//                            // 发送处理中的消息（在错误情况前）
//                            try {
//                                emitter.send(SseEmitter.event().name("processing").data("收到消息: \"" + message + "\"，正在处理中..."));
//                                emitter.send(SseEmitter.event().name("processing").data("开始处理消息..."));
//                            } catch (IOException ioException) {
//                                log.error("发送处理中消息失败", ioException);
//                            }
//
//                            log.error("处理消息时发生错误", error);
//                            try {
//                                emitter.send(SseEmitter.event().name("error").data("处理消息时发生错误: " + error.getMessage()));
//                            } catch (IOException e) {
//                                log.error("发送错误消息失败", e);
//                            }
//                            emitter.completeWithError(error);
//                        }
//                            ,
//                        () -> {
//                            try {
//                                emitter.send(SseEmitter.event().name("complete").data("[DONE]"));
//                                emitter.complete();
//                            } catch (IOException e) {
//                                log.error("完成消息发送失败", e);
//                                emitter.completeWithError(e);
//                            }
//                        }
//                    );
            } catch (Exception e) {
                emitter.completeWithError(e);
            }
        });

        return emitter;
    }
}